package com.example.smartcitydemo.ui.home.activity

import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import com.example.smartcity_jscs.network.ResultStates.Resource
import com.example.smartcitydemo.NEWS_DETAIL
import com.example.smartcitydemo.NEWS_SEARCH
import com.example.smartcitydemo.R
import com.example.smartcitydemo.base.BaseActivity
import com.example.smartcitydemo.bean.NewsInfo
import com.example.smartcitydemo.databinding.ActivitySearchResultBinding
import com.example.smartcitydemo.ext.init
import com.example.smartcitydemo.ui.home.MyNewsAdapter
import com.example.smartcitydemo.viewModel.home.HomeViewModel

class SearchResultActivity :
    BaseActivity<ActivitySearchResultBinding>(R.layout.activity_search_result) {
    private val homeViewModel: HomeViewModel by viewModels()
    private val searchNewsAdapter: MyNewsAdapter by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        MyNewsAdapter().apply {
            init()
            setDiffCallback(NewsInfo.diffCallBack)
            setOnItemClickListener { adapter, view, pos ->
                val newsDetailId = view.tag as Int
                val intent =
                    Intent(this@SearchResultActivity, NewsDetailActivity::class.java).apply {
                        putExtra(NEWS_DETAIL, newsDetailId)
                    }
                startActivity(intent)
            }
        }
    }

    override fun addObserver(contentView: ActivitySearchResultBinding) {
        homeViewModel.newsSearchResult.observe(this) {
            when (it) {
                is Resource.Success ->
                    searchNewsAdapter.setDiffNewData(it.data!!.toMutableList())
                is Resource.Failure ->
                    searchNewsAdapter.setEmptyView(R.layout.error_layout)
            }
        }
    }

    override fun initData() {
        val stringExtra = intent.getStringExtra(NEWS_SEARCH)
        homeViewModel.getNewsSearch(stringExtra ?: "")
    }

    override fun initView(contentView: ActivitySearchResultBinding, savedInstanceState: Bundle?) {
        contentView.run {
            newsSearchToolbar.tvContent.text = "新闻搜索"
            newsSearchRecycler.adapter = searchNewsAdapter
        }
    }
}